"use client"

import { useEffect } from "react"
import { User } from "@/types/admin"
import { useAdminStore } from "@/lib/store"
import { Button } from "@/components/ui/button"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form"
import { Input } from "@/components/ui/input"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import { zodResolver } from "@hookform/resolvers/zod"
import { useForm } from "react-hook-form"
import * as z from "zod"

// 创建两个不同的验证模式，一个用于创建用户，一个用于编辑用户
const createUserSchema = z.object({
  employeeId: z.string().min(1, "工号不能为空"),
  username: z.string().min(1, "用户名不能为空"),
  name: z.string().min(1, "姓名不能为空"),
  departmentId: z.string().min(1, "请选择部门"),
  roleId: z.string().min(1, "请选择角色"),
  email: z.string().email("请输入有效的邮箱地址").or(z.string().length(0)),
  phone: z.string().min(1, "电话号码不能为空"),
  status: z.enum(["active", "disabled"]),
  password: z.string().min(6, "密码至少需要6个字符"),
})

const editUserSchema = z.object({
  employeeId: z.string().min(1, "工号不能为空"),
  username: z.string().min(1, "用户名不能为空"),
  name: z.string().min(1, "姓名不能为空"),
  departmentId: z.string().min(1, "请选择部门"),
  roleId: z.string().min(1, "请选择角色"),
  email: z.string().email("请输入有效的邮箱地址").or(z.string().length(0)),
  phone: z.string().min(1, "电话号码不能为空"),
  status: z.enum(["active", "disabled"]),
  // 编辑模式下密码可以为空
  password: z.string().min(6, "密码至少需要6个字符").optional().or(z.string().length(0)),
})

interface UserDialogProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  user?: User
}

export function UserDialog({
  open,
  onOpenChange,
  user,
}: UserDialogProps) {
  const { departments, roles, users, addUser, updateUser } = useAdminStore()
  const isEditing = !!user

  // 根据是否编辑模式选择不同的验证模式
  const formSchema = isEditing ? editUserSchema : createUserSchema

  const defaultValues = {
    employeeId: "",
    username: "",
    name: "",
    departmentId: "",
    roleId: "",
    email: "",
    phone: "",
    status: "active" as const,
    password: "",
  }

  const form = useForm<z.infer<typeof formSchema>>({
    resolver: zodResolver(formSchema),
    defaultValues: isEditing && user ? {
      employeeId: user.employeeId,
      username: user.username,
      name: user.name,
      departmentId: user.department?.id || "",
      roleId: user.role?.id || "",
      email: user.email || "",
      phone: user.phone || "",
      status: user.status,
      password: "", // 编辑时不填充密码
    } : defaultValues,
  })

  // 监听对话框打开状态，重置表单
  useEffect(() => {
    if (open) {
      if (isEditing && user) {
        form.reset({
          employeeId: user.employeeId,
          username: user.username,
          name: user.name,
          departmentId: user.department?.id || "",
          roleId: user.role?.id || "",
          email: user.email || "",
          phone: user.phone || "",
          status: user.status,
          password: "", // 编辑时不填充密码
        })
      } else {
        form.reset(defaultValues)
      }
    }
  }, [open, user, form, isEditing])

  const onSubmit = (values: z.infer<typeof formSchema>) => {
    const department = departments.find(d => d.id === values.departmentId)
    const role = roles.find(r => r.id === values.roleId)

    if (!department || !role) {
      return
    }

    const userData = {
      employeeId: values.employeeId,
      username: values.username,
      name: values.name,
      department,
      role,
      email: values.email,
      phone: values.phone,
      status: values.status,
      lastLogin: user?.lastLogin || new Date().toISOString(),
      password: values.password || (user?.password || "123456"), // 如果没有新密码，保留旧密码或使用默认密码
    }

    if (isEditing && user) {
      updateUser(user.id, userData)
    } else {
      addUser(userData)
    }

    onOpenChange(false)
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[500px]">
        <DialogHeader>
          <DialogTitle>{isEditing ? "编辑用户" : "新增用户"}</DialogTitle>
          <DialogDescription>
            {isEditing
              ? "修改用户信息，点击保存确认更改。"
              : "添加新用户，填写完成后点击创建。"}
          </DialogDescription>
        </DialogHeader>
        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
            {/* 基本信息区域 */}
            <div className="space-y-2">
              <h3 className="text-sm font-medium text-muted-foreground">基本信息</h3>
              
              <div className="grid grid-cols-2 gap-4">
                <FormField
                  control={form.control}
                  name="employeeId"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>工号</FormLabel>
                      <FormControl>
                        <Input placeholder="输入工号" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={form.control}
                  name="name"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>姓名</FormLabel>
                      <FormControl>
                        <Input placeholder="输入姓名" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>

              <div className="grid grid-cols-2 gap-4">
                <FormField
                  control={form.control}
                  name="departmentId"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>所属部门</FormLabel>
                      <Select
                        onValueChange={field.onChange}
                        value={field.value}
                      >
                        <FormControl>
                          <SelectTrigger>
                            <SelectValue placeholder="选择部门" />
                          </SelectTrigger>
                        </FormControl>
                        <SelectContent>
                          {departments.map((dept) => (
                            <SelectItem key={dept.id} value={dept.id}>
                              {dept.name}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={form.control}
                  name="roleId"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>角色</FormLabel>
                      <Select
                        onValueChange={field.onChange}
                        value={field.value}
                      >
                        <FormControl>
                          <SelectTrigger>
                            <SelectValue placeholder="选择角色" />
                          </SelectTrigger>
                        </FormControl>
                        <SelectContent>
                          {roles.map((role) => (
                            <SelectItem key={role.id} value={role.id}>
                              {role.name}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>
            </div>

            {/* 账号信息区域 */}
            <div className="space-y-2 pt-2">
              <h3 className="text-sm font-medium text-muted-foreground">账号信息</h3>
              
              <FormField
                control={form.control}
                name="username"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>用户名</FormLabel>
                    <FormControl>
                      <Input placeholder="输入登录用户名" {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="password"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel className={isEditing ? "text-red-500" : ""}>
                      {isEditing ? "新密码" : "密码"}
                      {isEditing && <span className="text-xs ml-2 text-muted-foreground">(留空表示不修改)</span>}
                    </FormLabel>
                    <FormControl>
                      <Input 
                        type="password" 
                        placeholder={isEditing ? "留空表示不修改" : "输入密码"} 
                        {...field} 
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              
              <FormField
                control={form.control}
                name="status"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>状态</FormLabel>
                    <Select
                      onValueChange={field.onChange}
                      value={field.value}
                    >
                      <FormControl>
                        <SelectTrigger>
                          <SelectValue placeholder="选择状态" />
                        </SelectTrigger>
                      </FormControl>
                      <SelectContent>
                        <SelectItem value="active">正常</SelectItem>
                        <SelectItem value="disabled">禁用</SelectItem>
                      </SelectContent>
                    </Select>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>

            {/* 联系方式区域 */}
            <div className="space-y-2 pt-2">
              <h3 className="text-sm font-medium text-muted-foreground">联系方式</h3>
              
              <div className="grid grid-cols-2 gap-4">
                <FormField
                  control={form.control}
                  name="email"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>邮箱</FormLabel>
                      <FormControl>
                        <Input placeholder="输入邮箱地址" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={form.control}
                  name="phone"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>电话</FormLabel>
                      <FormControl>
                        <Input placeholder="输入电话号码" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>
            </div>

            <DialogFooter>
              <Button type="submit">
                {isEditing ? "保存" : "创建"}
              </Button>
            </DialogFooter>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  )
} 